// 企业碳积分碳行为分展示
import React, { Children, useEffect, useState, useRef } from 'react';
import { connect } from 'dva';
import './carbonCredits.less';
import { Table, Select, Button, Input } from 'antd';
import 'antd/dist/antd.css';
const { Option } = Select;
import { getCreditList, getCreditDictionariesList } from '@/services/carbon'

const carbonCredits = (props) => {
  // 表格总数据
  const [dataSource, setDataSource] = useState([]);
  // 分页数据
  const [pagination, setPagination] = useState({
    pageNum: 1,
    current: 1,
    pageSize: 20,
    total: 0,
  });
  // 企业查询筛选值
  const [enterpriseAbbrev, setEnterpriseAbbrev] = useState('');
  // 评级查询选项
  const [rateFilter, setRateFilter] = useState([]);
  // 评级查询筛选值
  const [rate, setRate] = useState('');
  // 一级行业选项
  const [industryFirstFilter, setIndustryFirstFilter] = useState([]);
  // 一级行业选值
  const [industryFirst, setindustryFirst] = useState('');
  // 二级行业选项
  const [industryScenedFilter, setIndustryScenedFilter] = useState([]);
  // 二级行业筛选值
  const [industryScened, setIndustryScened] = useState('');
  // 三级行业选项
  const [industryThirdFilter, setIndustryThirdFilter] = useState([]);
  // 三级行业选值
  const [industryThird, setIndustryThird] = useState('');
  // 年份选项
  const [yyyyFilter, setYyyyFilter] = useState([]);
  // 年份筛选值
  const [yyyy, setYyyy] = useState('');
  // 月份查询选项
  const [mmFilter, setMmFilter] = useState([]);
  // 月份查询选值
  const [mm, setMm] = useState('');
  // 表格自适应高度
  const [scrollY, setScrollY] = useState(0);
  const containerRef = useRef(null);
  // 表格自适应高度钩子
  useEffect(() => {
    const handleResize = () => {
      if (containerRef.current) {
        const containerHeight = containerRef.current.clientHeight;
        setScrollY(containerHeight - 290); // 100 是你想减去的像素值
      }
    };
    handleResize(); // 初始化时计算高度
    window.addEventListener('resize', handleResize); // 添加 resize 事件监听
    return () => {
      window.removeEventListener('resize', handleResize); // 清理事件监听
    };
  }, []);

  useEffect(() => {
    // 调用预计碳减排筛选项接口
    fetchCreditsFilterData('carbon_industry_first')
    // 调用表格数据接口
    fetchCreditsList()
  }, [])

  // 监听当前页发生改变，查询表格数据
  useEffect(() => {
    fetchCreditsList();
  }, [pagination.pageNum])

  // 获取筛选项接口
  const fetchCreditsFilterData = async (params) => {
    try {
      // 获取接口数据并赋值
      const res = await getCreditDictionariesList()
      if (res.code === 200) {
        setRateFilter(res.data.rateList)
        setIndustryFirstFilter(res.data.firstList)
        setIndustryScenedFilter(res.data.scenedList)
        setIndustryThirdFilter(res.data.thirdList)
        setYyyyFilter(res.data.yearList)
        setMmFilter(res.data.monthList)
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 获取表格数据接口
  const fetchCreditsList = async (params) => {
    try {
      // 拼接页数数据及筛选项数据，获取接口数据并赋值
      const res = await getCreditList({ ...pagination, enterpriseAbbrev: enterpriseAbbrev, rate: rate, industryFirst: industryFirst, industryScened: industryScened, industryThird: industryThird, yyyy: yyyy, mm: mm })
      if (res.code === 200) {
        setDataSource(res)
        setPagination({ ...pagination, total: res.total })
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 切换当前页，修改当前页的值，再触发监听钩子
  const handlePaginationChange = (page) => {
    setPagination({ ...pagination, pageNum: page, current: page });
  };

  // 处理搜索按钮点击事件
  const handleSearch = (params) => {
    // 当前页为第一页时，不改变当前页直接直接调用接口，否则将当前页设置成第一页
    if (pagination.pageNum === 1) {
      fetchCreditsList()
    } else {
      setPagination({ ...pagination, pageNum: 1, current: 1 });
    }
  };

  // 表格列配置
  const columns = [
    { title: '企业简称', dataIndex: 'enterpriseAbbrev', key: 'enterpriseAbbrev', width: '15%', align: 'center' },
    { title: '绿色评级', dataIndex: 'rate', key: 'rate', width: "10%", align: 'center' },
    { title: '一级行业', dataIndex: 'industryFirst', key: 'industryFirst', width: "10%", align: 'center' },
    { title: '二级行业', dataIndex: 'industryScened', key: 'industryScened', width: "10%", align: 'center' },
    { title: '三级行业', dataIndex: 'industryThird', key: 'industryThird', width: "15%", align: 'center' },
    { title: '年份', dataIndex: 'yyyy', key: 'yyyy', width: "10%", align: 'center' },
    { title: '月份', dataIndex: 'mm', key: 'mm', width: "10%", align: 'center' },
    { title: '碳积分', dataIndex: 'carbonCredit', key: 'carbonCredit', width: "10%", align: 'center' },
    { title: '碳行为积分', dataIndex: 'carbonBehavior', key: 'carbonBehavior', width: "10%", align: 'center' }
  ];

  return (
    <div className="carbonCredits-content">
      <div className="content-box">
        <div className="filter-container">
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">企业查找:</span>
              <Input
                style={{ flex: 1 }}
                placeholder="请输入想要查找的企业简称"
                value={enterpriseAbbrev}
                onChange={e => setEnterpriseAbbrev(e.target.value)}
              />
            </div>
            <div className="filter-item">
              <span className="filter-name">一级行业查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的一级行业"
                onChange={value => setindustryFirst(value)}
                allowClear
              >
                {industryFirstFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
            <div className="filter-item">
              <span className="filter-name">年份查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的年份"
                onChange={value => setYyyy(value)}
                allowClear
              >
                {yyyyFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div className="filter-row">
            <div className="filter-item">
              <span className="filter-name">评级查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的评级"
                onChange={value => setRate(value)}
                allowClear
              >
                {rateFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
            <div className="filter-item">
              <span className="filter-name">二级行业查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的二级行业"
                onChange={value => setIndustryScened(value)}
                allowClear
              >
                {industryScenedFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
            <div className="filter-item">
              <span className="filter-name">月份查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的月份"
                onChange={value => setMm(value)}
                allowClear
              >
                {mmFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
          </div>
          <div className="filter-row">
          <div className="filter-item">
            </div>
            <div className="filter-item">
              <span className="filter-name">三级行业查询:</span>
              <Select
                style={{ flex: 1 }}
                placeholder="请选择想要查找的三级行业"
                onChange={value => setIndustryThird(value)}
                allowClear
              >
                {industryThirdFilter.map((option, index) => (
                  <Option key={index} value={option.dictValue}>
                    {option.dictLabel}
                  </Option>
                ))}
              </Select>
            </div>
            <div className="filter-item">
              <Button type="primary" onClick={handleSearch} className="searchBtn">
                搜索
              </Button>
            </div>
          </div>
        </div>
        <div className="table-container" ref={containerRef}>
          <Table
            dataSource={dataSource.rows}
            columns={columns}
            pagination={{
              ...pagination,
              showSizeChanger: false,
              pageSizeOptions: [],
              onChange: handlePaginationChange,
            }}
            scroll={{ y: scrollY }}
          />
        </div>
      </div>
    </div>
  )
};

export default connect()(carbonCredits);
